<template>
  <div class="header-search" :class="{'show': isShow}">
    <i class="icon-container el-icon-search" @click.stop="toggeleSearch" />
    <el-select
      ref="headerSearchSelect"
      v-model="search"
      filterable
      default-first-option
      remote
      :remote-method="querySearch"
      placeholder="Search"
      class="header-search-select"
    >
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
  </div>
</template>
<script>
export default {
  name: 'HeaderSearch',
  data() {
    return {
      search: '',
      options: [
        {
          label: '荔枝',
          value: '荔枝'
        },
        {
          label: '龙眼',
          value: '龙眼'
        }
      ],
      isShow: false
    }
  },
  watch: {
    isShow: {
      handler(value) {
        if (value) {
          document.body.addEventListener('click', this.close)
        } else {
          document.body.removeEventListener('click', this.close)
        }
      },
      deep: true
    }
  },
  methods: {
    querySearch(query) {},
    toggeleSearch() {
      this.isShow = !this.isShow
      if (this.isShow) {
        this.options = []
        this.$refs.headerSearchSelect && this.$refs.headerSearchSelect.focus()
        this.$nextTick(() => {
          setTimeout(() => {
            this.options = [
              {
                label: '荔枝',
                value: '荔枝'
              },
              {
                label: '龙眼',
                value: '龙眼'
              }
            ]
          }, 300)
        })
      } else {
        this.close()
      }
    },
    close() {
      // 清空数据
      this.options = []
      this.search = ''
      // 取消选择框的选中
      this.$refs.headerSearchSelect && this.$refs.headerSearchSelect.blur()
      this.isShow = false
    }
  }
}
</script>

<style lang="scss" scoped>
.header-search {
  font-size: 0px !important;
  .el-icon-search {
    display: inline-block;
    width: 46px;
    height: 50px;
    line-height: 50px;
    font-size: 18px;
    font-weight: bold;
    text-align: center;
    cursor: pointer;
    vertical-align: middle;
  }
  .header-search-select {
    font-size: 18px;
    transition: width .2s;
    width: 0;
    overflow: hidden;
    background: transparent;
    border-radius: 0;
    display: inline-block;
    vertical-align: middle;

    ::v-deep .el-input__inner {
      border: 0;
      border-radius: 0;
      border-bottom: 1px solid #ccc;
      padding-left: 0;
      padding-right: 0;
      vertical-align: middle;
    }
  }
  &.show {
    .header-search-select {
      width: 210px;
    }
  }
}
</style>
